package 算法.leetcode.labuladong.数组和链表;

/**
 * @author lchenglong
 * @date 2022/6/16
 */
public class 最长回文子串 {
    static class Solution {

        public static void main(String[] args) {
            Solution solution = new Solution();
            String ans = solution.longestPalindrome("babad");
            System.out.println(ans);
        }
        public String longestPalindrome(String s) {
            String res = "";
            for (int i=0;i<s.length();i++) {
                // 以 s[i] 为中⼼的最⻓回⽂⼦串
                String s1 = palindrome(s,i,i);
                // 以 s[i] 和 s[i+1] 为中⼼的最⻓回⽂⼦串
                String s2 = palindrome(s,i,i+1);
                // res = longest(res, s1, s2)
                res = s1.length()>res.length()?s1:res;
                res = s2.length()>res.length()?s2:res;
            }
            return res;
        }

        public String  palindrome(String s,int l,int r) {
            while (l>=0&&r<s.length()&&s.charAt(l) == s.charAt(r)){
                l--;
                r++;
            }
            return s.substring(l+1,r);
        }
    }
}
